package com.hengpeng.itfin.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.exception.TransException;
import com.hengpeng.itfin.service.PaymentService;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.AccountType;
import com.hengpeng.itfinbase.en.TradeMode;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.idAssign.ID;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.CashResponseMsg;
import com.hengpeng.itfinbase.message.partner.DrawReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.DrawReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.DrawReconciliationResponseMsg.CashReconciliationDto;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.PayRequestMsg;
import com.hengpeng.itfinbase.message.partner.PayResponseMsg;
import com.hengpeng.itfinbase.message.partner.QueryTransDetailRequest;
import com.hengpeng.itfinbase.message.partner.QueryTransDetailResponse;
import com.hengpeng.itfinbase.message.partner.QueryTransStatRequest;
import com.hengpeng.itfinbase.message.partner.QueryTransStatResponse;
import com.hengpeng.itfinbase.message.partner.SaveReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.SaveReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.SaveReconciliationResponseMsg.SaveReconciliationDto;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.MessageTemplates;
import com.hengpeng.itfinbase.persist.Payment;
import com.hengpeng.itfinbase.persist.Payment.PayStatus;
import com.hengpeng.itfinbase.persist.Payment.PaymentType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.ibm.icu.math.BigDecimal;

/**
 * <pre>
 * 支付系统服务实现
 * </pre>
 * 
 * @author zhaojitao
 * @version 1.0, 2015-6-4
 */
@Service
@Lazy
public class PaymentServiceImpl extends BaseServiceImpl implements PaymentService {

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void packPayRequest(PayRequestMsg request) {
        Payment payment = new Payment();
        payment.setType(PaymentType.IMPREST);
        payment.setProviderId(request.getProviderId());
        if (request.getAccountType() == AccountType.PLATFORM) {// 平台充值
            String orderId = ID.getInstanse().getID(18).toString();
            UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().get(request.getUserId());
            if (user == null) {
                throw new TransException("用户不存在！");
            }
            request.setOrdId(orderId);
            request.setOrdDate(DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
            request.setUsrCustId(user.getTrustAccountId());
        } else {
            UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().get(request.getUserId());
            if (user == null) {
                throw new TransException("用户不存在！");
            }
            Account account = serviceFactory.getAccountService().getAccount(user.getId());
            request.setOrdDate(DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
            request.setUsrCustId(user.getTrustAccountId());
            Double doubleMoney = Double.parseDouble(request.getTransAmt()) * 100;
            payment.setMoney(doubleMoney.longValue());
            payment.setUserId(request.getUserId());
            payment.setAccountType(request.getAccountType());
            payment.setCreateTime(new Date());
            payment.setIsReconcil(BoolValue.NO);
            payment.setRequestTime(new Date());
            payment.setStatus(PayStatus.PAYING);
            payment.setTrustAccountId(request.getUsrCustId());
            payment.setUserAgent(request.getUserAgent());
            payment.setUserName(user.getUserName());
            payment.setAccountId(account.getId());
        }
        payment = serviceFactory.getDaoFactory().getCommonDao().saveEntity(payment);
        if (payment.getId() != null) {
            request.setOrdId(payment.getId().toString());
        } else {
            throw new TransException("充值记录保存失败！");
        }
    }

    @Override
    public ServiceResult<Payment> dealPayResult(PayResponseMsg msg) {
        ServiceResult<Payment> result = new ServiceResult<Payment>();
        Payment payment = serviceFactory.getDaoFactory().getCommonDao()
                .getEntity(Payment.class, Long.parseLong(msg.getOrdId()));
        if (payment != null) {
            if (msg.getRespCode().equals(RespCodeConstants.CommonCode.TRANS_SUC)) {
                if (payment.getStatus() == PayStatus.PAYING) {
                    Double feeAmt = 0d;
                    if (!StringHelper.isEmpty(msg.getFeeAmt())) {
                        feeAmt = Double.parseDouble(msg.getFeeAmt().replaceAll(",", "")) * 100;
                    }
                    int i = serviceFactory.getPaymentService().updateStatus(PayStatus.PAYING, PayStatus.SUCCESS,
                            new Date(), new Date(), feeAmt.longValue(), Long.parseLong(msg.getOrdId()));
                    if (i > 0) {
                        serviceFactory.getAccountService().changeAccountMoney(payment.getUserId(),
                                Long.parseLong(String.valueOf(payment.getMoney())), 0l, 0l, 0l, TransType.IMPREST,
                                TradeMode.ADD, String.valueOf(payment.getId()), "充值成功");
                        // changeAccountMoney(payment.getUserId(),
                        // Long.parseLong(String.valueOf(payment.getMoney())),
                        // TransType.IMPREST, TradeMode.ADD,
                        // String.valueOf(payment.getId()), "充值成功");

                        // 站内信 充值
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("date", new Date());
                        map.put("money", MoneyUtil.convertFenToYuan(payment.getMoney()));
                        serviceFactory.getMessageService().asynsendSystemMessageByTypeWithUsrCustId(
                                payment.getTrustAccountId(), MessageTemplates.BusiType.M310.name(), map);
                    }
                }
                result.setIsSuccess(true);
                result.setMessage(RespCodeConstants.CommonCode.TRANS_SUC);
                result.setCode(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
                return result;
            } else {
                serviceFactory.getPaymentService().updateStatus(PayStatus.PAYING, PayStatus.FAILED, new Date(),
                        new Date(), 0l, Long.parseLong(msg.getOrdId()));

                // 站内信 充值
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("date", new Date());
                map.put("money", MoneyUtil.convertFenToYuan(payment.getMoney()));
                serviceFactory.getMessageService().asynsendSystemMessageByTypeWithUsrCustId(
                        payment.getTrustAccountId(), MessageTemplates.BusiType.M311.name(), map);

                result.setIsSuccess(false);
                result.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL);
                result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
                return result;
            }
        } else {
            // 未找到充值记录
            result.setIsSuccess(false);
            result.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL);
            result.setCode(RespCodeConstants.CommonCode.DATA_NOT_FOUND);
            return result;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void packDrawRequest(CashRequestMsg request) {
        Payment payment = new Payment();
        payment.setType(PaymentType.DRAW);
        payment.setProviderId(request.getProviderId());
        if (request.getAccountType() == AccountType.PLATFORM) {
            // 平台取现，暂不记录本地记录
            UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().get(request.getUserId());
            if (user == null) {
                throw new TransException("用户不存在！");
            }
            String orderId = ID.getInstanse().getID(18).toString();
            request.setOrdId(orderId);
            request.setOrdDate(DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
            request.setUsrCustId(user.getTrustAccountId());
        } else {
            UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().get(request.getUserId());
            if (user == null) {
                throw new TransException("用户不存在！");
            }
            // Double doubleMoney = Double.parseDouble(request.getTransAmt()) *
            // 100;
            Double doubleMoney = ((new BigDecimal(request.getTransAmt())).multiply(new BigDecimal("100")))
                    .doubleValue();
            Account account = serviceFactory.getAccountService().getAccount(user.getId());
            if (account.getBaseMoney() - account.getFreezeMoney() < doubleMoney) {
                throw new TransException("金额不足！");
            }
            request.setOrdDate(DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
            request.setUsrCustId(user.getTrustAccountId());
            payment.setMoney(doubleMoney.longValue());
            payment.setUserId(request.getUserId());
            payment.setAccountType(request.getAccountType());
            payment.setCreateTime(new Date());
            payment.setIsReconcil(BoolValue.NO);
            payment.setRequestTime(new Date());
            payment.setStatus(PayStatus.PAYING);
            payment.setTrustAccountId(request.getUsrCustId());
            payment.setUserAgent(request.getUserAgent());
            payment.setUserName(user.getUserName());
            payment.setAccountId(account.getId());
            payment = serviceFactory.getDaoFactory().getCommonDao().saveEntity(payment);
            if (payment.getId() != null) {
                request.setOrdId(payment.getId().toString());
                serviceFactory.getAccountService().changeAccountMoney(payment.getUserId(),
                        Long.parseLong(String.valueOf(payment.getMoney())), 0l, 0l, 0l, TransType.DRAW,
                        TradeMode.FREEZE, String.valueOf(payment.getId()), "提现冻结");
                // changeAccountMoney(payment.getUserId(),
                // Long.parseLong(String.valueOf(payment.getMoney())),
                // TransType.DRAW, TradeMode.FREEZE,
                // String.valueOf(payment.getId()), "提现冻结");
            } else {
                throw new TransException("提现记录保存失败！");
            }

        }
    }

    @Override
    public void drawQuery() {
        List<Payment> list = serviceFactory.getDaoFactory().getPaymentDao()
                .queryList(PaymentType.DRAW, PayStatus.PAYING);
        if (list != null && list.size() > 0) {
            // PoolServer poolServer = new PoolServer(50);
            for (final Payment p : list) {
                // poolServer.executeTask(new Runnable() {
                // public void run() {
                serviceFactory.getPaymentService().doDrawQuery(p);
                // }
                // });
            }
            // poolServer.endServer();
        }
    }

    @Override
    public void imprestQuery() {
        List<Payment> list = serviceFactory.getDaoFactory().getPaymentDao()
                .queryList(PaymentType.IMPREST, PayStatus.PAYING);
        if (list != null && list.size() > 0) {
            // PoolServer poolServer = new PoolServer(50);
            for (final Payment p : list) {
                // poolServer.executeTask(new Runnable() {
                // public void run() {
                serviceFactory.getPaymentService().doImprestQuery(p);
                // }
                // });
            }
            // poolServer.endServer();
        }
        
    }
    
    @Override
    public void doImprestQuery(Payment payment) {
        Date time = DateTimeUtil.addSecond(payment.getCreateTime(),
                Long.parseLong(SystemConfigUtil.getConfigValue(SystemConfigConstants.INVEST_LIMIT_TIME)));
        if (time.getTime() < System.currentTimeMillis()) {
            QueryTransDetailRequest request = new QueryTransDetailRequest();
            request.setOrdId(payment.getId().toString());
            request.setPartnerTransType(PartnerTransType.QueryTransDetail);
            request.setQueryTransType("SAVE");//充值
            QueryTransDetailResponse response = (QueryTransDetailResponse) serviceFactory.getPartnerService().request(
                    request);
            PayResponseMsg payResponseMsg = new PayResponseMsg();
            payResponseMsg.setOrdId(payment.getId().toString());
            payResponseMsg.setFeeAmt(response.getFeeAmt());
            if ("S".equals(response.getTransStat()) || "F".equals(response.getTransStat())
                    || "I".equals(response.getTransStat())){// 初始状态，失败，成功
                if ("S".equals(response.getTransStat())) {//成功
                    
                } else if ("F".equals(response.getTransStat())) {//失败
                    
                } else if ("I".equals(response.getTransStat())) {//初始
                    
                }
                ServiceResult<Payment> resulst = serviceFactory.getPaymentService().dealPayResult(payResponseMsg);
                logger.info("充值交易状态查询定时作业：订单id:" + payResponseMsg.getOrdId() + ",响应消息:" + resulst.getMessage()
                        + ",响应码:" + resulst.getCode() + "");
            }
        }
        
    }

    @Override
    public void doDrawQuery(Payment payment) {
        Date time = DateTimeUtil.addSecond(payment.getCreateTime(),
                Long.parseLong(SystemConfigUtil.getConfigValue(SystemConfigConstants.INVEST_LIMIT_TIME)));
        if (time.getTime() < System.currentTimeMillis()) {
            /**
             * <pre>
             * 当提现人提现时,超过指定时间还未完成提现,则系统进行交易状态查询,
             * 查询结果若为交易失败,则进行释放提现冻结操作
             * 查询结果若为交易成功,则进行交易信息的补充成功操作.
             * </pre>
             */
            QueryTransStatRequest request = new QueryTransStatRequest();
            request.setOrdId(payment.getId().toString());
            request.setOrdDate(DateTimeUtil.formatToStr(payment.getCreateTime(), DateTimeUtil.DATE_FORMAT_YYYYMMDD));
            request.setPartnerTransType(PartnerTransType.QueryTransStat);
            request.setQueryTransType("CASH");
            QueryTransStatResponse response = (QueryTransStatResponse) serviceFactory.getPartnerService().request(
                    request);
            final CashResponseMsg cashResponseMsg = new CashResponseMsg();
            cashResponseMsg.setOrdId(payment.getId().toString());
            /**
             * 本作业处理未提交订单的情况 ,S--成功 ,F--失败 ,H--经办 ,R--拒绝
             */
            if (RespCodeConstants.ChinaPnrCode.CASH_NOT_FOUND.equals(response.getRespCode())
                    || "S".equals(response.getTransStat()) || "F".equals(response.getTransStat())
                    || "H".equals(response.getTransStat()) || "R".equals(response.getTransStat())) {
                if (RespCodeConstants.ChinaPnrCode.CASH_NOT_FOUND.equals(response.getRespCode())
                        || "F".equals(response.getTransStat()) || "R".equals(response.getTransStat())) {// 没有记录,失败,拒绝
                    cashResponseMsg.setRespCode(RespCodeConstants.AccountCode.CASH_ERRCODE_FAIL);
                } else if ("S".equals(response.getTransStat())) {// 成功
                    cashResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANS_SUC);
                } else if ("H".equals(response.getTransStat())) {// 经办
                    cashResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANSMESSAGE_ERRCODE_DEALING);
                }
                ServiceResult<Payment> resulst = serviceFactory.getPaymentService().dealDrawResult(cashResponseMsg);
                logger.info("取现交易状态查询定时作业：订单id:" + cashResponseMsg.getOrdId() + ",响应消息:" + resulst.getMessage()
                        + ",响应码:" + resulst.getCode() + "");
            }
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateStatus(PayStatus oldStatus, PayStatus newStatus, Date updateTime, Date overTime, Long chargemoney,
            Long orderId) {
        return serviceFactory.getDaoFactory().getPaymentDao()
                .updateStatus(oldStatus, newStatus, updateTime, overTime, chargemoney, orderId);
    }

    @Override
    public ServiceResult<Payment> dealDrawResult(CashResponseMsg msg) {
        ServiceResult<Payment> result = new ServiceResult<Payment>();
        Payment payment = serviceFactory.getDaoFactory().getCommonDao()
                .getEntity(Payment.class, Long.parseLong(msg.getOrdId()));
        if (payment != null) {
            if (payment.getStatus() == PayStatus.PAYING) {
                if (msg.getRespCode().equals(RespCodeConstants.CommonCode.TRANS_SUC)) {
                    Double feeAmt = 0d;
                    if (!StringHelper.isEmpty(msg.getFeeAmt())) {
                        feeAmt = Double.parseDouble(msg.getFeeAmt().replaceAll(",", "")) * 100;
                    }
                    int i = serviceFactory.getPaymentService().updateStatus(PayStatus.PAYING, PayStatus.SUCCESS,
                            new Date(), new Date(), feeAmt.longValue(), Long.parseLong(msg.getOrdId()));
                    if (i > 0) {
                        serviceFactory.getAccountService().changeAccountMoney(
                                payment.getUserId(),
                                Long.parseLong(String.valueOf(payment.getMoney())),
                                0L,
                                0L,
                                feeAmt.longValue(),
                                TransType.DRAW,
                                TradeMode.SUBTRACT,
                                String.valueOf(payment.getId()),
                                "提现成功,扣款：" + String.valueOf(payment.getMoney()) + ",解冻："
                                        + String.valueOf(payment.getMoney()) + ";提现手续费" + feeAmt.longValue());

                        // 站内信 取现
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("date", new Date());
                        map.put("money", MoneyUtil.convertFenToYuan(payment.getMoney()));
                        serviceFactory.getMessageService().asynsendSystemMessageByTypeWithUsrCustId(
                                payment.getTrustAccountId(), MessageTemplates.BusiType.M210.name(), map);
                    }

                } else if (msg.getRespCode().equals(RespCodeConstants.CommonCode.TRANSMESSAGE_ERRCODE_DEALING)) {// 处理中
                    /**
                     * 处理中状态不处理
                     */
                } else if (msg.getRespCode().equals(RespCodeConstants.AccountCode.CASH_ERRCODE_FAIL)) {// 失败
                    int i = serviceFactory.getPaymentService().updateStatus(PayStatus.PAYING, PayStatus.FAILED,
                            new Date(), new Date(), 0l, Long.parseLong(msg.getOrdId()));
                    if (i > 0) {
                        serviceFactory.getAccountService().changeAccountMoney(payment.getUserId(),
                                Long.parseLong(String.valueOf(payment.getMoney())), 0l, 0l, 0l, TransType.DRAW,
                                TradeMode.UNFREEZE, String.valueOf(payment.getId()), "提现失败解冻");
                        // changeAccountMoney(payment.getUserId(),
                        // Long.parseLong(String.valueOf(payment.getMoney())),
                        // TransType.DRAW, TradeMode.UNFREEZE,
                        // String.valueOf(payment.getId()), "提现失败解冻");

                        // 站内信 取现
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("date", new Date());
                        map.put("money", MoneyUtil.convertFenToYuan(payment.getMoney()));
                        serviceFactory.getMessageService().asynsendSystemMessageByTypeWithUsrCustId(
                                payment.getTrustAccountId(), MessageTemplates.BusiType.M211.name(), map);
                    }
                }
            }
            result.setIsSuccess(true);
            result.setMessage(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
            result.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
            return result;
        } else {
            // 未找到充值记录
            result.setIsSuccess(false);
            result.setMessage(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            result.setCode(RespCodeConstants.CommonCode.DATA_NOT_FOUND);
            return result;
        }
    }

    @Override
    public Payment findByOrderId(String orderId) {
        DynamicQuery query = new DynamicQuery(Payment.class);
        query.eq("orderId", orderId);
        return serviceFactory.getPersistService().getByDynamicQuery(Payment.class, query);
    }

    @Override
    public Payment findByOrderIdAndProviderId(String orderId, String providerId) {
        DynamicQuery query = new DynamicQuery(Payment.class);
        query.eq("orderId", orderId);
        query.eq("providerId", providerId);
        return serviceFactory.getPersistService().getByDynamicQuery(Payment.class, query);
    }

    @Override
    public void saveReconciliation(Integer pageNum, Integer pageSize, Date beginDate, Date endDate) {
        SaveReconciliationResponseMsg responseMsg = serviceFactory.getPaymentService().doSaveReconciliation(pageNum,
                pageSize, beginDate, endDate);
        if (!StringHelper.isEmpty(responseMsg.getTotalItems())
                && (pageNum * pageSize) < Integer.parseInt(responseMsg.getTotalItems())) {
            saveReconciliation(pageNum + 1, pageSize, beginDate, endDate);
        }
    }

    @Override
    public SaveReconciliationResponseMsg doSaveReconciliation(Integer pageNum, Integer pageSize, Date beginDate,
            Date endDate) {
        SaveReconciliationRequestMsg reqMsg = new SaveReconciliationRequestMsg();
        reqMsg.setBeginDate(DateTimeUtil.formatToStr(beginDate, DateTimeUtil.DATE_FORMAT_YYYYMMDD));
        reqMsg.setEndDate(DateTimeUtil.formatToStr(endDate, DateTimeUtil.DATE_FORMAT_YYYYMMDD));
        reqMsg.setPageNum(pageNum.toString());
        reqMsg.setPageSize(pageSize.toString());
        reqMsg.setPartnerTransType(PartnerTransType.SaveReconciliation);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        SaveReconciliationResponseMsg responseMsg = (SaveReconciliationResponseMsg) serviceFactory.getPartnerService()
                .request(reqMsg);
        /**
         * 处理结果
         */
        List<SaveReconciliationDto> reconciliationInfos = responseMsg.getSaveReconciliationDtoList();
        if (reconciliationInfos != null && reconciliationInfos.size() > 0) {
            // PoolServer poolServer = new PoolServer(50);
            for (SaveReconciliationDto dto : reconciliationInfos) {
                final PayResponseMsg payResponseMsg = new PayResponseMsg();
                payResponseMsg.setOrdId(dto.getOrdId());
                if ("S".equals(dto.getTransStat()) || "F".equals(dto.getTransStat())) {// 处理成功或失败失败
                    if ("S".equals(dto.getTransStat())) {// 成功
                        payResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANS_SUC);
                        payResponseMsg.setRespDesc(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
                    } else if ("F".equals(dto.getTransStat())) {// 失败
                        payResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANS_FAIL);
                        payResponseMsg.setRespDesc(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
                    }
                    // poolServer.executeTask(new Runnable() {
                    // @Override
                    // public void run() {
                    serviceFactory.getPaymentService().dealPayResult(payResponseMsg);
                    // }
                    // });
                } else if ("I".equals(dto.getTransStat())) {// 初始
                    /**
                     * 初始状态：用户还没有输入密码确认的充值 初始状态暂不处理
                     */
                }
            }
            // poolServer.endServer();
        }
        return responseMsg;
    }

    @Override
    public void drawReconciliation(Integer pageNum, Integer pageSize, Date beginDate, Date endDate) {
        DrawReconciliationResponseMsg responseMsg = serviceFactory.getPaymentService().doDrawReconciliation(pageNum,
                pageSize, beginDate, endDate);

        if (!StringHelper.isEmpty(responseMsg.getTotalItems())
                && (pageNum * pageSize) < Integer.parseInt(responseMsg.getTotalItems())) {
            drawReconciliation(pageNum + 1, pageSize, beginDate, endDate);
        }

    }

    @Override
    public DrawReconciliationResponseMsg doDrawReconciliation(Integer pageNum, Integer pageSize, Date beginDate,
            Date endDate) {
        DrawReconciliationRequestMsg reqMsg = new DrawReconciliationRequestMsg();
        reqMsg.setBeginDate(DateTimeUtil.formatToStr(beginDate, DateTimeUtil.DATE_FORMAT_YYYYMMDD));
        reqMsg.setEndDate(DateTimeUtil.formatToStr(endDate, DateTimeUtil.DATE_FORMAT_YYYYMMDD));
        reqMsg.setPageNum(pageNum.toString());
        reqMsg.setPageSize(pageSize.toString());
        reqMsg.setPartnerTransType(PartnerTransType.CashReconciliation);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        DrawReconciliationResponseMsg responseMsg = (DrawReconciliationResponseMsg) serviceFactory.getPartnerService()
                .request(reqMsg);
        /**
         * 处理结果
         */
        List<CashReconciliationDto> reconciliationInfos = responseMsg.getCashReconciliationDtoList();
        if (reconciliationInfos != null && reconciliationInfos.size() > 0) {
            // PoolServer poolServer = new PoolServer(50);
            for (CashReconciliationDto dto : reconciliationInfos) {
                final CashResponseMsg cashResponseMsg = new CashResponseMsg();
                cashResponseMsg.setOrdId(dto.getOrdId());
                if ("S".equals(dto.getTransStat()) || "F".equals(dto.getTransStat()) || "I".equals(dto.getTransStat())
                        || "H".equals(dto.getTransStat()) || "R".equals(dto.getTransStat())) {
                    if ("S".equals(dto.getTransStat())) {// 成功
                        cashResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANS_SUC);
                        cashResponseMsg.setRespDesc(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
                    } else if ("F".equals(dto.getTransStat())) {// 失败
                        cashResponseMsg.setRespCode(RespCodeConstants.AccountCode.CASH_ERRCODE_FAIL);
                    } else if ("I".equals(dto.getTransStat())) {// 初始
                        cashResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANSMESSAGE_ERRCODE_DEALING);
                    } else if ("H".equals(dto.getTransStat())) {// 经办
                        cashResponseMsg.setRespCode(RespCodeConstants.CommonCode.TRANSMESSAGE_ERRCODE_DEALING);
                    } else if ("R".equals(dto.getTransStat())) {// 拒绝
                        cashResponseMsg.setRespCode(RespCodeConstants.AccountCode.CASH_ERRCODE_FAIL);
                    }
                    serviceFactory.getPaymentService().dealDrawResult(cashResponseMsg);
                }
                // poolServer.executeTask(new Runnable() {
                // @Override
                // public void run() {
                // serviceFactory.getPaymentService().dealDrawResult(cashResponseMsg);
                // }
                // });
            }
            // poolServer.endServer();
        }
        return responseMsg;
    }
}
